import datetime
import json
import os

from alipay import AliPay
from django.conf import settings
from django.db import transaction
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse

from common.func import is_login
from django_redis import get_redis_connection
from .models import MXorder,MXorderdetail
from goods.models import MXgoods
# Create your views here.

@is_login
def order(request):
    redis_cli = get_redis_connection('cart')
    redis_data = json.loads(redis_cli.get('redis_data_%d' % request.user.id).decode())

    select_data = {}
    for gid in redis_data:
        if redis_data[gid]['selected'] == '1':
            select_data[int(gid)] = int(redis_data[gid]['num'])

    # 生成一个订单号
    order_code = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(request.user.id)

    # 开启事务
    with transaction.atomic():

        # 设置保存点
        save_id = transaction.savepoint()
        order = MXorder.objects.create(
            uid=request.user.id,
            order_code=order_code,
            total_count=sum(select_data.values()),
            total_amount=0
        )

        total_price = 0

        for gid,gcount in select_data.items():
            while True:
                good = MXgoods.objects.get(id=gid)

                if gcount > good.storenums:
                    transaction.savepoint_rollback(save_id)
                    return HttpResponse('该商品库存不够')

                update_flag = MXgoods.objects.filter(id=gid,storenums=good.storenums).update(
                    storenums=good.storenums - gcount,
                    productnum=good.productnum + gcount
                )

                # print(request.user.id, good.storenums, good.productnum)

                if not update_flag:
                    continue

                order_detail = MXorderdetail.objects.create(
                    uid=request.user.id,
                    order_code=order_code,
                    goods_id=good.id,
                    counts=gcount,
                    price=good.dis
                )
                total_price += good.dis * gcount

                del redis_data[str(gid)]
                break
        order.total_amount = total_price
        order.save()

        redis_cli.set('redis_data_%d' % request.user.id,json.dumps(redis_data))

        transaction.savepoint_commit(save_id)
    return redirect(reverse('orders:order_detail',args=(order_code,)))





@is_login
def order_detail(request,order_code):
    order = MXorder.objects.get(order_code=order_code)
    orderdes = MXorderdetail.objects.filter(order_code=order_code)

    data_list = []
    for orderdetail in orderdes:
        good = MXgoods.objects.get(id=orderdetail.goods_id)
        # print(good.name)
        data_dict = {
            'img':good.img,
            'name':good.name,
            'price':orderdetail.price,
            'counts':orderdetail.counts
        }
        data_list.append(data_dict)
    # print(data_list)
    context = {
        'order_code':order_code,
        'total_amount':order.total_amount,
        'goods':data_list
    }
    return render(request,'order.html',context)

@is_login
def pay(request,order_code):
    alipay = AliPay(
        appid='2016101700705082',
        app_notify_url=None,  # 默认回调url, 要返回一个真实的域名
        app_private_key_path=os.path.join(settings.BASE_DIR, "alipay/app_private_key.txt"),
        alipay_public_key_path=os.path.join(settings.BASE_DIR, "alipay/alipay_public_key.txt"),
        sign_type="RSA2",
        debug=True
    )

    # 生成登录支付宝连接
    order = MXorder.objects.get(order_code=order_code)
    order_string = alipay.api_alipay_trade_page_pay(
        out_trade_no=order_code,
        total_amount=order.total_amount,
        subject='美西订单',
        return_url='http://127.0.0.1:8000/payback/',
    )

    # print(order_string)

    alipay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
    return redirect(alipay_url)


@is_login
def payback(request):
    query_dict = request.GET
    data = query_dict.dict()

    print(data)
    # 获取并从请求参数中剔除signature
    signature = data.pop('sign')

    # 创建支付宝支付对象
    alipay = AliPay(
        appid='2016101700705082',
        app_notify_url=None,  # 默认回调url
        app_private_key_path=os.path.join(settings.BASE_DIR, "alipay/app_private_key.txt"),
        alipay_public_key_path=os.path.join(settings.BASE_DIR, "alipay/alipay_public_key.txt"),
        sign_type="RSA2",
        debug=True
    )
    # 校验这个重定向是否是alipay重定向过来的
    success = alipay.verify(data, signature)
    if success:
        #	验证成功
        # 生成支付记录，改变订单状态
        order_code = data['out_trade_no']
        MXorder.objects.filter(order_code=order_code).update(status=2)

        return redirect(reverse('index:info'))
    else:
        # 验证失败
        return HttpResponse('支付失败')
